package com.gitee.beiding.template_excel;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;

import java.util.List;
import java.util.Map;

/*

 */

//模板行的包装
class TemplateRow {

    //如果行不为null则该字段不为null
    private WorkRow extractRow;

    //私有构造器
    private TemplateRow() {

    }

    private ColNumberMatchingMode colNumberMatchingMode = ColNumberMatchingMode.EQUALS;

    static TemplateRow compile(XSSFRow xssfRow, Map<Integer, Merge> mergeMap, Map<String, List<ValueHolder>> colValueMap, ColNumberMatchingMode colModel) {

        if (xssfRow != null) {
            TemplateRow row = new TemplateRow();
            short firstCellNum = xssfRow.getFirstCellNum();
            short lastCellNum = xssfRow.getLastCellNum();

            WorkRow extractRow = new WorkRow(colValueMap);
            row.extractRow = extractRow;
            row.colNumberMatchingMode = colModel;
            extractRow.setFirstCol(firstCellNum);
            extractRow.setLastCol(lastCellNum);

            for (int i = firstCellNum; i < lastCellNum; i++) {

                Merge merge = mergeMap.get(i);
                if (merge == null) {
                    merge = Merge.get(1, 1);
                }

                XSSFCell cell = xssfRow.getCell(i);

                if (cell == null) {
                    extractRow.compile(i, null, merge);
                } else {
                    extractRow.compile(i, PoiUtils.readCell(cell), merge);
                }

            }

            return row;
        } else {
            return null;
        }


    }

    //是否正在搜索匹配规则的行
    private boolean finding = true;


    //提取一行,如果能够提取到结果就返回提取到的Map,否则返回null
    boolean extract(XSSFRow xssfRow, Map<Integer, Merge> mergeMap) {

        int firstCellNum = this.extractRow.getFirstCol();
        int lastCellNum = this.extractRow.getLastCol();

        for (int i = firstCellNum; i < lastCellNum; i++) {
            Merge merge = mergeMap.get(i);
            if (merge == null) {
                merge = Merge.get(1, 1);
            }

            Object v = null;
            XSSFCell cell = xssfRow.getCell(i);
            if (cell != null) {
                v = PoiUtils.readCell(cell);
            }

            if (!this.extractRow.extract(i, v, merge)) {
                return finding;
            }

        }

        //已经找到符合条件的位置
        finding = false;

        //返回本行中提取的结果
        return true;
    }

}
